package com.cloudpark.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudpark.common.util.ObjectUtil;
import com.cloudpark.model.entity.Plate;
import com.cloudpark.model.entity.UserPlate;
import com.cloudpark.model.mapper.PlateMapper;
import com.cloudpark.model.mapper.UserPlateMapper;
import com.cloudpark.model.vo.PlateVo;
import com.cloudpark.service.PlateService;

@Service
public class PlateServiceImpl implements PlateService {
	
	@Autowired
	private PlateMapper plateMapper;
	@Autowired
	private UserPlateMapper userPlateMapper;

	@Override
	public List<PlateVo> queryPlateList(Long uid) {
		return plateMapper.selectByUid(uid);
	}

	@Override
	public boolean savePlate(String plateNumber, Long uid) {
		Plate plate = null;
		List<Plate> list = plateMapper.selectByPlateNumber(plateNumber);
		if (ObjectUtil.isBlank(list)) {
			plate = new Plate();
			plate.setPlateNumber(plateNumber);
			plateMapper.insert(plate);
		} else {
			plate = list.get(0);
		}
		UserPlate userPlate = new UserPlate();
		userPlate.setUid(uid);
		userPlate.setPid(plate.getId());
		
		// is already bind
		List<UserPlate> existList = userPlateMapper.selectByUserPlate(userPlate);
		if (ObjectUtil.isNotBlank(existList)) {
			return true;
		} else {
			userPlateMapper.insert(userPlate);
		}
		return false;
	}

	@Override
	public void deleteUserPlate(Long pid, Long uid) {
		UserPlate userPlate = new UserPlate();
		userPlate.setPid(pid);
		userPlate.setUid(uid);
		userPlateMapper.deleteUserPlate(userPlate);
	}

	@Override
	public Plate queryByPlateNumber(String plateNumber) {
		List<Plate> list = plateMapper.selectByPlateNumber(plateNumber);
		if (ObjectUtil.isNotBlank(list)) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public Plate queryById(Long id) {
		return plateMapper.selectByPrimaryKey(id);
	}

}
